<?php

namespace app\YoucaiWeb\controller;
use app\YoucaiWeb\model\UserType;
use think\Controller;
use think\Db;
use org\Verify;

class Login extends Controller
{

    /**
     * 登录页面
     * @return
     */
    public function index()
    {
        $this->assign('verify_type', config('verify_type'));
        return $this->fetch('/login');
    }


    /**
     * 登录操作
     * @return
     */
    public function doLogin()
    {
        $username = input("param.username");
        $password = input("param.password");
        $result = $this->validate(compact('username', 'password'), 'AdminValidate');
        if(true !== $result){
            return json(['code' => -5, 'url' => '', 'msg' => $result]);
        }
        $verify = new Verify();
        $hasUser = Db::name('admin')->where('ad_name', $username)->find();
        if(empty($hasUser)){
            return json(['code' => -1, 'url' => '', 'msg' => '管理员不存在']);
        }
        if(md5($password)!= $hasUser['ad_pwd']){
            writelog($hasUser['ad_id'],$username,'用户【'.$username.'】登录失败：密码错误',1,3);
            return json(['code' => -2, 'url' => '', 'msg' => '账号或密码错误']);
        }
        if(1 != $hasUser['ad_state']){
            writelog($hasUser['id'],$username,'用户【'.$username.'】登录失败：该账号被禁用',1,3);
            return json(['code' => -6, 'url' => '', 'msg' => '该账号被禁用']);
        }

        //获取该管理员的角色信息
        $user = new UserType();
        $info = $user->getRoleInfo($hasUser['ad_rid']);
        session('uid', $hasUser['ad_id']);         //用户ID
        session('username', $hasUser['ad_name']);  //用户名
        session('rolename', $info['title']);    //角色名
        session('rule', $info['rules']);        //角色节点
        session('name', $info['name']);         //角色权限
  
        //更新管理员状态
        $param = [
            'ad_count' => $hasUser['ad_count'] + 1,
            'ad_logip' => request()->ip(),
            'ad_ltime' => time(),
        ];
        Db::name('admin')->where('ad_id', $hasUser['ad_id'])->update($param);
        writelog($hasUser['ad_id'],session('username'),'用户【'.session('username').'】登录成功',1,1);
        return json(['code' => 1, 'url' => url('index/index'), 'msg' => '登录成功！']);
    }


    /**
     * 验证码
     * @return
     */
    public function checkVerify()
    {
        $verify = new Verify();
        $verify->imageH = 32;
        $verify->imageW = 100;
		$verify->codeSet = '0123456789';
        $verify->length = 4;
        $verify->useNoise = false;
        $verify->fontSize = 14;
        return $verify->entry();
    }


    /**
     * 退出登录
     * @return
     */
    public function loginOut()
    {
        session(null);
        cache('db_config_data',null);//清除缓存中网站配置信息
        $this->redirect('login/index');
    }
}